<template>
  <!-- 导航栏 -->
  <van-nav-bar title="产品详情" left-text="" left-arrow @click-left="goBack" @click-right="showShare = true">
    <template #right>
        <van-icon name="ellipsis" size="20" />
    </template>
  </van-nav-bar>
  <!-- 轮播图 -->
  <van-swipe :autoplay="3000" lazy-render>
    <van-swipe-item v-for="item in info.thumbs_list">
      <img :src="item" height="300" fit="cover" />
    </van-swipe-item>
  </van-swipe>
  <div class="clear"></div>
  <div class="detailbox">
    <h4>{{info.name}}</h4>
    <div class="price" style="color: #EE0A24;font-size: 25px;">
      <em>单独购买￥</em>{{ info.price }} |
      <em>拼团价格￥</em>{{ info.team }}
      <em style="float: right;color: #b7b7bf;">库存{{ info.stock }}件</em>
    </div>
  </div>
  <div class="allkbox"></div>

  <div class="info_choice">
    <!-- Sku 商品规格 -->
    <div class="commodity" @click="SkuShow=true">
      <div class="opt">
        <div class="title wanl-gray">
          选择
        </div>
        <div class="option">
          <div class="selected">
            <div>
              <span>尺码</span>
              <span>颜色</span>
            </div>
          </div>
          <div class="option-list">
            <div>
              <div class="cu-tag">
                <span>155/80A/S</span>
              </div>
              <div class="cu-tag">
                <span>160/84A/M1</span>
              </div>
              <div class="cu-tag">
                <span>65/88A/L</span>
              </div>
              <div class="cu-tag">
                <span>更多规格可选</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray" onclick="location.href = './sku.html' ">
        <img src="/assets/images/go.png">
      </div>
    </div>
    <!-- 服务 -->
    <div class="commodity" @click="showServe=true">
      <div class="opt">
        <div class="title wanl-gray">
          服务
        </div>
        <div class="option">
          <div class="selected">
            <div>
              <span>7天无理由退款</span>
              <span>·</span>
              <span>24小时内发货</span>
              <span>·</span>
              <span>假一赔十</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="clear"></div>
  <div class="allkbox"></div>
  <div class="clear"></div>
  <!-- 参数和评价 -->
  <div class="detailbox_2">
    <van-tabs v-model:active="TabActive" type="card" color="#ee0a24">
      <van-tab title="产品参数">
        <div v-html="info.content"></div>
      </van-tab>
      <van-tab title="商品评价">
        <div class="rate">
          <div class="rate-header">
              <div class="rate-score">
                  <h4>与描述相符</h4>
                  <strong>{{star}}</strong>
              </div>
              <div class="rate-graph">
                <van-rate v-model="star" allow-half readonly/>
              </div>
          </div>
          <div class="rate-content">
              <div>
                  <div class="review-box" v-for="item in commentInfo">
                      <div class="review-item">
                          <div class="from-whom">
                              <div class="avatar">
                                  <img :src="item.business.avatar_text" alt="" />
                              </div>
                              <div class="name">{{item.business.name}}</div>
                          </div>
                          <div class="review-details">
                            <van-rate v-model="item.rate_text" void-color="#eee" color="#ffbb4e" allow-half readonly/>
                              <div class="content">{{item.comment_text}}</div>
                              <div >
                                  <img v-for="img in item.thumbs_list" :src="img" alt="">
                              </div>
                              <div class="time">{{item.createtime}}</div>
                          </div>
                      </div>
                  </div>
              </div>
              <div>
                  <!-- <div class="rate-empty">该商品还没有人写评价呢</div> -->
              </div>
          </div>
      </div>
      </van-tab>
    </van-tabs>
  </div>
  <div class="clear"></div>
  <div class="h54"></div>
  <div class="footerbox">
    <div class="footer2">
      <van-action-bar>
        <router-link :to="{path:'/product/customer', query:{pid: info.id}}">
          <van-action-bar-icon icon="chat-o" text="客服"/>
        </router-link>
        <van-action-bar-icon icon="cart-o" text="购物车" :badge="info.count"  @click="toCartPage"/>
        <van-action-bar-icon v-show="info.iscollect" icon="like" text="取消收藏" @click="collect"/>
        <van-action-bar-icon v-show="!info.iscollect" icon="like-o" text="收藏" @click="collect"/>
        <van-action-bar-button type="danger" text="立即购买" @click="SkuShow=true"/>
      </van-action-bar>
    </div>
  </div>
  <!-- 拼团信息 -->
  <div class="teamwork">
    <img src="/assets/images/teamwork.jpg" alt="">
  </div>
  <!-- 分享面板 -->
  <div class="share">
    <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="sharelist" />
  </div>

  <!-- 协议条款 -->
  <van-action-sheet v-model:show="showServe" title="协议条款">
    <div class="ProductTip">
        三、我们如何使用信息 <br />
        四、我们如何共享信息<br />
        五、我们如何转让信息<br />
        六、我们如何公开披露信息<br />
        七、一般储存期限<br />
        八、我们如何确保您的信息安全<br />
        九、您能做什么<br />
        十、我们如何处理未成年人的个人信息<br />
        十一、您的个人信息的存储地点<br />
        十二、本隐私权政策不适用的范围<br />
        十三、本隐私权政策如何更新<br />
        十四、联系我们<br />
    </div>
  </van-action-sheet>

  <!-- SKU -->
  <!-- properties商品属性和规格 @add-cart加入购物车时触发 @buy-click购买时触发 -->
  <van-sku id="sku" ref="SkuRef" v-model="SkuShow" :sku="sku" :goods="goods" :properties="properties" :goods-id="info.id" @add-cart="AddCart" @buy-clicked="Buy">
    <template #sku-actions="props">
        <div class="van-sku-actions">
            <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">
               加入购物车
            </van-button>
            <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">
                单独购买
            </van-button>
            <van-button square size="large" type="danger" @click="toTeamJoinPage">
                参与拼团
            </van-button>
            <van-button square size="large" type="danger" @click="toTeamPage">
              发起拼团
            </van-button>
        </div>
    </template>
  </van-sku>
</template>

<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css'
const { proxy } = getCurrentInstance()
const LoginUser = reactive(proxy.$cookies.get("LoginUser") ?? {})
const goBack = () => { proxy.$router.go(-1) }

// 评论信息
const commentInfo=ref([]);
// 商品星级
const star=ref(5);

// 展开分享面板
const showShare = ref(false)
const sharelist = [
    [
        { name: '微信', icon: 'wechat' },
        { name: '朋友圈', icon: 'wechat-moments' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
    ],
    [
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
        { name: '小程序码', icon: 'weapp-qrcode' },
    ],
]

// sku插件
let SkuShow = ref(false)
let sku = ref({})
let properties = ref([])
let goods = ref({})
let SkuRef = ref({})
// 展开服务条款
const showServe = ref(false)
let TabActive = ref(0)

const pid = ref(proxy.$route.query.pid ?? 0)
const info=ref()
// 挂载前加载出数据
onBeforeMount(()=>{
  getProductInfo()
})
const getProductInfo = async ()=>{
  // 商品信息
  let result=await Api.ProductDetail({productid:pid.value,busid:LoginUser.id})
  if (result.code == 1) {
    // 商品信息
    let productData=result.data.productinfo;
    // sku信息
    let skuData=result.data.sku;
    // 商品属性列表
    let propertiesData=result.data.properties;

    info.value=productData;
    sku.value=skuData;
    goods.value = { picture: productData.thumbs_text }
    properties.value = Object.values(propertiesData)
  }

  // 商品评价
  let res=await Api.ProductComment({proid:pid.value})
  if (res.code == 1) {
    let nums=ref(0);
    commentInfo.value=res.data.list;
    commentInfo.value.forEach(item => {
      let name=item.business.nickname[0]+'***'
      item.business.name=name
      nums.value+=parseFloat(item.rate)
    })
    star.value=(nums.value/res.data.count).toFixed(1);
    console.log(commentInfo.value);
  }
}

// 收藏商品
const collect=async ()=>{
  let result=await Api.ProductCollect({productid:pid.value,busid:LoginUser.id})
  if (result.code == 1) {
    showSuccessToast({
      message: result.msg
    })
    setInterval(() => {
      window.location.reload()
    }, 1000);
  }else{
    showFailToast(result.msg);
  }
}

// 加入购物车
const AddCart = async (skuData)=>{
  // 判断是否有登陆 JSON.stringify转为JSON字符串
  if(JSON.stringify(LoginUser)=='{}'){
    showFailToast({
      message: '未登陆，请先登录',
    })
    proxy.$router.push('/business/login')
    return false;
  }

  // 判断是否有选择规格
  if(properties.value.length>0 && !skuData.selectedSkuComb){
    showFailToast('请选择商品规格')
    return false;
  }

  // 获取购买数量
  let selectedNum =skuData.selectedNum
  if(selectedNum<0){
    showFailToast('购买数量不能小于等于0')
    return false;
  }

  // 选中的属性id值
  var relationids=[]
  // 获取选中的属性对象
  if(properties.value.length){
    let SkuProps=skuData.selectedSkuComb.properties;
    for (var item of SkuProps) {
            var id = item.v[0] ? item.v[0]['id'] : 0;
            if (id) relationids.push(id)
        }
  }

  let params={
    busid:LoginUser.id,
    proid:pid.value,
    nums:selectedNum,
    relationids:relationids.join(',') //规格id
  }
  let result=await Api.CartAdd(params)

  // 隐藏弹出框
  SkuShow.value=false
  if(result.code==0){
    showFailToast(result.msg);
  }else{
    info.value.count=result.data
    showSuccessToast(result.msg)
  }
}

// 单独购买
const Buy=(skuData)=>{
  // 判断是否有登陆 JSON.stringify转为JSON字符串
  if(JSON.stringify(LoginUser)=='{}'){
    showFailToast({
      message: '未登陆，请先登录',
    })
    proxy.$router.push('/business/login')
    return false;
  }

  // 判断是否有选择规格
  if(properties.value.length>0 && !skuData.selectedSkuComb){
    showFailToast('请选择商品规格')
    return false;
  }

  // 获取购买数量
  let selectedNum =skuData.selectedNum
  if(selectedNum<0){
    showFailToast('购买数量不能小于等于0')
    return false;
  }

  // 选中的属性id值
  var relationids=[]
  // 获取选中的属性对象
  if(properties.value.length){
    let SkuProps=skuData.selectedSkuComb.properties;
    for (var item of SkuProps) {
            var id = item.v[0] ? item.v[0]['id'] : 0;
            if (id) relationids.push(id)
        }
  }

  proxy.$router.push({
    path: '/product/onlyconfirm',
    query: {
      proid: pid.value,
      nums:selectedNum,
      relationids:relationids.join(',')
    }
  })

}

// 跳转购物车
const toCartPage = () => {proxy.$router.push('/gwc/index')}



// 发起拼团
const toTeamPage = () => {
  // 判断是否有登陆 JSON.stringify转为JSON字符串
  if(JSON.stringify(LoginUser)=='{}'){
    showFailToast({
      message: '未登陆，请先登录',
    })
    proxy.$router.push('/business/login')
    return false;
  }

  let skuData=SkuRef.value.getSkuData()

  // 判断是否有选择规格
  if(properties.value.length>0 && !skuData.selectedSkuComb){
    showFailToast('请选择商品规格')
    return false;
  }

  // 获取购买数量
  let selectedNum =skuData.selectedNum
  if(selectedNum<0){
    showFailToast('购买数量不能小于等于0')
    return false;
  }

  // 选中的属性id值
  var relationids=[]
  // 获取选中的属性对象
  if(properties.value.length){
    let SkuProps=skuData.selectedSkuComb.properties;
    for (var item of SkuProps) {
            var id = item.v[0] ? item.v[0]['id'] : 0;
            if (id) relationids.push({
              id: id,
              name: item.v[0]['name'] ?? ''
            })
            console.log(item);
        }
  }

  proxy.$cookies.set("relationids",JSON.stringify(relationids))
  proxy.$router.push({
    path:'/team/add',
    query:{
      proid:pid.value,
      nums:selectedNum
    }
  })
}

// 参与拼团 跳转参与的商品拼团列表
const toTeamJoinPage = () => {
  // 判断是否有登陆 JSON.stringify转为JSON字符串
  if(JSON.stringify(LoginUser)=='{}'){
    showFailToast({
      message: '未登陆，请先登录',
    })
    proxy.$router.push('/business/login')
    return false;
  }

  let skuData=SkuRef.value.getSkuData()

  // 判断是否有选择规格
  if(properties.value.length>0 && !skuData.selectedSkuComb){
    showFailToast('请选择商品规格')
    return false;
  }

  // 获取购买数量
  let selectedNum =skuData.selectedNum
  if(selectedNum<0){
    showFailToast('购买数量不能小于等于0')
    return false;
  }

  // 选中的属性id值
  var relationids=[]
  // 获取选中的属性对象
  if(properties.value.length){
    let SkuProps=skuData.selectedSkuComb.properties;
    for (var item of SkuProps) {
            var id = item.v[0] ? item.v[0]['id'] : 0;
            if (id) relationids.push({
              id: id,
              name: item.v[0]['name'] ?? ''
            })
        }
  }

  // 选中的属性id值
  var attrsid=[]
  // 获取选中的属性对象
  if(properties.value.length){
    let SkuProps=skuData.selectedSkuComb.properties;
    for (var item of SkuProps) {
            var id = item.v[0] ? item.v[0]['id'] : 0;
            if (id) attrsid.push(id)
        }
  }

  proxy.$cookies.set("relationids",JSON.stringify(relationids))
  proxy.$router.push({
    path:'/team/add',
    query:{
      proid:pid.value,
      nums:selectedNum,
      action:'join',
      attrs:attrsid.join(',')
    }
  })
}
</script>

<style>
.showShare .van-share-sheet__options {
    justify-content: center;
}

.van-tabs__nav--card {
    margin: 0;
}
#sku{
  z-index: 9999 !important;
}
.van-sku-group-container{
  text-align: left;
}
.review-box{
  text-align: left;
}
</style>